package com.zzh.jetpackdemo.manager

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.work.*
import com.zzh.jetpackdemo.R
import com.zzh.jetpackdemo.manager.worker.MyWorker
import kotlinx.android.synthetic.main.activity_manager.*
import java.util.concurrent.TimeUnit

private val TAG = ManagerActivity::class.java.name


class ManagerActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_manager)
        var data = Data.Builder()
            .putString("zzh", "pam")
            .build()
        var work = OneTimeWorkRequest.Builder(MyWorker::class.java)
            .setConstraints(constraints) //设置触发条件
            .addTag("zzh")
            .setInputData(data)
            .build()
        start.setOnClickListener {
            WorkManager.getInstance(this@ManagerActivity).enqueue(work)
        }
        WorkManager.getInstance(this@ManagerActivity).getWorkInfoByIdLiveData(work.id)
            .observe(this@ManagerActivity,
                Observer<WorkInfo> { t ->
                    Log.i(TAG, "onCreate: status=>${t.state}")
                    showNowWorker?.text =
                        "state => ${t.state} \n value => ${t.outputData.getString("value")}"
                    Log.i(
                        TAG,
                        "onChanged: ${t.outputData.getString("value")}"
                    )
                })
    }

    var constraints: Constraints = Constraints.Builder()
        .setRequiresCharging(true)
        .setRequiredNetworkType(NetworkType.CONNECTED)
        .setRequiresBatteryNotLow(true)
        .build()


}